package com.fivefu.core.init;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivefu.core.pojo.FFTableMapper;
import com.fivefu.core.pojo.FfDataSource;
import com.fivefu.core.mapper.FfTableMapperMapper;
import com.fivefu.core.param.FFTableMapperParam;
import com.fivefu.core.service.FfDataSourceService;
import com.fivefu.core.util.DataSourceUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/4
 */
@Component
@Order(10)
public class DemoInit implements ApplicationRunner {

    @Autowired
    FfDataSourceService ffDataSourceService;
    @Autowired
    FfTableMapperMapper ffTableMapperMapper;

    public void initDataSource() {
        System.out.println("开始执行初始化数据源操作");
        QueryWrapper<FfDataSource> queryWrapper = new QueryWrapper<>();
        List<FfDataSource> list = ffDataSourceService.list(queryWrapper.eq("is_valid", 1));
        DataSourceUtil.addDataSourceListToDynamic(list);
    }

    public void initTableMapper(){
        System.out.println("开始执行初始化表映射操作");
        QueryWrapper<FFTableMapper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_valid",1);
        List<FFTableMapper> list = ffTableMapperMapper.selectList(queryWrapper);
        Map<String,String> tableMapper = new HashMap<>();
        Map<String,String> tableReverseMapper = new HashMap<>();
        list.forEach( a ->{
            tableMapper.put(a.getOriginTableName(),a.getExposeTableName());
            tableReverseMapper.put(a.getExposeTableName(),a.getOriginTableName());
        });
        FFTableMapperParam.setTableMapperMap(tableMapper);
        FFTableMapperParam.setTableMapperReverseMap(tableReverseMapper);

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        initDataSource();
        initTableMapper();
    }
}
